package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.JwTransfer;
import com.dianban.entity.JwUserAccount;
import com.dianban.entity.User;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.JwTransferService;
import com.dianban.service.JwUserAccountService;
import com.dianban.service.UserService;
import com.dianban.utils.DateUtils;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Api(value = "ApiTransferController", description = "提现控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/transfer/")
public class ApiTransferController extends BaseController {

    @Autowired
    private FacePayConfigService facePayConfigService;
    @Autowired
    private JwTransferService jwTransferService;
    @Autowired
    private JwUserAccountService jwUserAccountService;
    @Autowired
    private UserService userService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "佣金提现记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<JwTransfer> transfers = new ArrayList<>();
        try {
            transfers = jwTransferService.findList(user.getId(), null);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(transfers, "获取成功");
    }

    @ApiOperation(notes = "apply", httpMethod = "POST", value = "佣金提现")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "number", value = "提现金额", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "apply", method = RequestMethod.POST)
    public ResultVo apply(String number, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        // 处理实时的,不然这里会有问题,用户没退出的话一直是之前登录进来拥有的金额,就会有问题
        user = userService.findById(user.getId());
        JwTransfer jwTransfer = new JwTransfer();
        try {
            if (user.getFacePayCommission().compareTo(new BigDecimal(number)) <= 0) {
                return ResultVo.error(ResultCode.ERROR, "可用余额超出请求数额");
            }
            // 每天只能一次
            List<JwTransfer> jwTransfers = jwTransferService.findList(user.getId(), DateUtils.formatNow("yyyy-MM-dd"));
            if (!CollectionUtils.isEmpty(jwTransfers)) {
                return ResultVo.error(ResultCode.ERROR, "今日提现次数已用完");
            }
            List<JwUserAccount> jwUserAccounts = jwUserAccountService.find(user.getId(), "1");
            if (CollectionUtils.isEmpty(jwUserAccounts)) {
                return ResultVo.error(ResultCode.ERROR, "请先完善收款信息");
            }
            JwUserAccount jwUserAccount = jwUserAccounts.get(0);
            if (StringUtils.isEmpty(jwUserAccount.getFrontImage())) {
                return ResultVo.error(ResultCode.ERROR, "请先完善身份信息");
            }
            if (StringUtils.isEmpty(jwUserAccount.getFaceImage())) {
                return ResultVo.error(ResultCode.ERROR, "请先完善人脸照片");
            }
            if (StringUtils.isEmpty(jwUserAccount.getFlexResult()) || !"open".equals(jwUserAccount.getFlexResult())) {
                return ResultVo.error(ResultCode.ERROR, "已收到您的人脸照片,等待后台进行开户,1~2小时后再申请");
            }
            List<FacePayConfig> facePayConfigList = facePayConfigService.find(80, 1, null);
            BigDecimal commissionWithdrawService = new BigDecimal(6.5);
            if (facePayConfigList != null && !facePayConfigList.isEmpty()) {
                commissionWithdrawService = new BigDecimal(facePayConfigList.get(0).getValue());
            }
            BigDecimal service = new BigDecimal(number).multiply(commissionWithdrawService).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            BigDecimal cash = new BigDecimal(number).subtract(service).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            // 手续费问题
            jwTransfer.setTransferId(user.getId());
            jwTransfer.setReceiverId(0L);
            jwTransfer.setTransfer(user.getMobile());
            jwTransfer.setReceiver("");
            jwTransfer.setCoupon(new BigDecimal(number).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            jwTransfer.setService(service);
            jwTransfer.setCash(cash);
            jwTransfer.setStatus(-2);
            jwTransfer.setSource(10);
            jwTransfer.setSn(UUID.randomUUID().toString().replaceAll("-", ""));
            jwTransfer.setCreatetime(System.currentTimeMillis() / 1000);
            jwTransfer.setUpdatetime(System.currentTimeMillis() / 1000);
            jwTransfer.setName(jwUserAccount.getName());
            jwTransfer.setBankcard(jwUserAccount.getBankcard());
            jwTransfer.setBankName(jwUserAccount.getBankName());
            jwTransfer.setIdcard(jwUserAccount.getIdcard());
            jwTransfer.setPhone(jwUserAccount.getPhone());
            jwTransferService.insert(jwTransfer);
            // 扣除相应的奖励
            userService.updateFacePayCommissionAndMoneyLog(new BigDecimal(number), user);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "服务异常");
        }
        return ResultVo.success(jwTransfer, "操作成功");
    }
}
